/**
 * 该文件为留言板功能相关接口
 */
const express=require("express");
const router=express.Router();

//引入passport模块
const passport = require("passport");

//引入数据库ImageModel
const MessageBoardModel=require("../../../models/messageBoard/index.js");

//引入全局输出类
const JsonResult=require("../../global/JsonResult.js");

// 引入查询条件和配置项
const UnityParams=require("../../conditions/unityParams.js");

// 添加评论接口（/api/messageBoard/add）
router.post("/add",passport.authenticate("jwt",{session:false}),(req,res,next)=>{
    // console.log(req.body);
    let messageBoards=new MessageBoardModel({
        userId:req.body.userId,
        content:req.body.content,
        from:req.body.from,
        to:req.body.to,
        isTop:req.body.isTop,
        parentId:req.body.parentId,
        email:req.body.email
    });
    messageBoards.save().then((doc)=>{
        res.json(JsonResult.success("添加评论成功",null));
    }).catch((error)=>{
        console.log(error.message);
        res.status(500).json(JsonResult.databaseError("数据库添加信息出错",null));
    });
});

const UserModel=require("../../../models/User.js");
const ImageModel=require("../../../models/Images.js");
// 查询评论接口（/api/messageBoard）
router.get("",passport.authenticate("jwt",{session:false}),async (req,res,next)=>{
    try {
        let counts=UnityParams.counts;
        let unityDataObj=UnityParams.unityDataObj(req.query);
        let unityOptionsObj=UnityParams.unityOptionsObj(req.query);
        let query=MessageBoardModel.find({...unityDataObj,parentId:0},null,{...unityOptionsObj,sort:{createdAt:-1}}).select("-__v");
        let data=await query.lean();
        let promises=data.map((item)=>{
            return MessageBoardModel.find({parentId:item._id},null,{sort:{createdAt:-1}}).select("-__v").lean();
        });
        counts=await MessageBoardModel.countDocuments();
        let list=await Promise.all(promises);
        list=list.filter((item)=>{
            return item.length>0;
        });
        // 获取每个用户的头像
        let emailData=data.map((item)=>{
            return ImageModel.find({email:item.email}).select("image email").lean();
        });
        let emailDalaList=await Promise.all(emailData);
        emailDalaList=emailDalaList.filter((item)=>{
            return item.length>0;
        });
        // async function getUserImage(obj){
        //     let emailDataArr=UserModel.find({_id:obj.userId}).select("email").lean();
        //     let emailData=await emailDataArr;
        //     // console.log(emailData);
        //     let imgDataArr=ImageModel.find({email:emailData[0].email}).select("image").lean();
        //     // console.log(await imgDataArr);
        //     let imgData=await imgDataArr;
        //     return imgData[0];
        // };
        // console.log(emailDalaList);
        data.forEach((item)=>{
            if(list.length == 0){
                item.items=[];
            }else{
                list.forEach((item1)=>{
                    if(item1.length >0 && item._id == item1[0].parentId){
                        item1.forEach((item3)=>{
                            if(emailDalaList.length == 0){
                                item3.image="";
                            }else{
                                emailDalaList.forEach((item4)=>{
                                    if(item4.length >0 && item3.email == item4[0].email){
                                        item3.image=item4[0].image;
                                    }else if(!item3.image){
                                        item3.image="";
                                    };
                                });
                            };
                        });
                        item.items=item1;
                    }else if((item.items && item.items.length == 0) || !item.items){
                        item.items=[];
                    };
                });
            };
            if(emailDalaList.length == 0){
                item.image="";
            }else{
                emailDalaList.forEach((item2)=>{
                    if(item2.length >0 && item.email == item2[0].email){
                        item.image=item2[0].image;
                    }else if(!item.image){
                        item.image="";
                    };
                });
            };
        });
        res.json(JsonResult.success("查询成功",{
            currentPage:req.query.pageNum?req.query.pageNum:1,
            currentSize:req.query.pageSize?req.query.pageSize:5,
            total:counts,
            data
        }));
    } catch (error) {
        console.log(error);
        res.status(500).json(JsonResult.databaseError("查询信息出错",null));  
    };
});

module.exports=router;